<template>
	<view class="container">
		<navbar title="分类" :toBack="false"></navbar>
		<view class="search u-flex" :style="{paddingTop: (navbarHeight + 14) + 'px'}">
			<u-input v-model="keyWord" placeholder="请输入关键字进行搜索" :customStyle="searchCustomStyle"
				:placeholderStyle="searchPlaceholderStyle" fontSize="28rpx" @confirm="searchChange" clearable>
				<template slot="prefix">
					<image class="img" src="https://qn.mtj.cdydsy.com/user_client/static/icons/ss.png"></image>
				</template>
				<template slot="suffix">
					<button class="button" @tap="searchChange">搜索</button>
				</template>
			</u-input>
		</view>
		<loading-page mode="zoom" :show="isLoading"></loading-page>
		<view class="main" v-if="!isLoading">
			<view class="header" id="header">
				<u-tabs ref="uTabs" :current="currentIndex" :list="efficacyList" @click="tabsClick" keyName="name"
					lineWidth="112rpx" lineColor="#000000" :inactiveStyle="tabInactiveStyle"
					:activeStyle="tabActiveStyle" :itemStyle="tabsItemStyle"></u-tabs>
			</view>
			<view class="category u-flex u-col-start">
				<scroll-view :scroll-top="verticalNavTop" scroll-with-animation scroll-y="true"
					:style="{height: residueHeight+'px'}" class="scroll-left">
					<view class="category-left">
						<view :class="['li u-flex-center',categoryIndex == k ?'li-active':'']"
							v-for="(val,k) in categoryList" :key="k" @click="categoryChange(k)">
							<view class="line" v-if="categoryIndex == k"></view>
							<view class="li-text">{{val.name}}</view>
						</view>
					</view>
				</scroll-view>
				<view class="category-right">
					<view class="right-header u-flex-between">
						<view class="header-text">{{categoryList[categoryIndex].name}}</view>
						<view class="header-right u-flex">
							<view :class="['new', { 'new-active': params.order_type === 2 }]" @click="setOrderType(2)">
								新品
							</view>
							<view :class="['new', { 'new-active': params.order_type === 3 }]" @click="setOrderType(3)">
								价格
							</view>
							<image class="header-icon" :src="riseIconSrc" v-if="params.price_order !== 2"></image>
							<image class="header-icon" :src="dropIconSrc"
								v-if="params.order_type === 3 && params.price_order === 2"></image>
						</view>
					</view>
					<view>
						<z-paging ref="paging" :fixed="false" v-model="productList" @query="getProductList"
							:height="(residueHeight - 30) + 'px'" loading-more-no-more-text="到底了" :auto="false"
							auto-show-system-loading>
							<view class="product" v-if="total > 0">
								<view class="li u-flex u-col-start" v-for="(item,index) in productList" :key="index"
									@click="productChange(item)">
									<view class="li-img">
										<u-image :src="item.cover_image" width="164rpx" height="164rpx"
											radius="8"></u-image>
										<image class="img-11" v-if="item.is_medical_product"
											:src="item.advance_money?'https://qn.mtj.cdydsy.com/user_client/static/11/index-img.png':'https://qn.mtj.cdydsy.com/user_client/static/11/index-imgs.png'">
										</image>
									</view>
									<view class="li-right u-flex-col u-flex-between u-col-start">
										<view class="li-name">{{item.name}}</view>
										<view class="li-footer u-flex-between">
											<view :class="['footer-left u-flex',item.advance_money?'':'u-col-end']">
												<view class="li-price">
													<span
														style="font-size: 24rpx;color: #CC242B;line-height: 28rpx;">￥</span>
													<span style="font-size: 28rpx;color: #CC242B;">{{item.price}}</span>
												</view>
												<view class="activity u-flex u-col-end" v-if="item.advance_money">
													<image class="activity-img"
														src="https://qn.mtj.cdydsy.com/user_client/static/11/activity-img.png">
													</image>
													<view class="activity-price">￥{{item.advance_money}}</view>
												</view>
												<view class="original-price" v-else>
													¥{{item.minPriceSpec.original_price}}
												</view>
											</view>
											<view class="footer-right">
												<view class="shop-base" v-if="item.source_type == 1"
													@click.stop="addShop(item)">
													<u-icon name="shopping-cart" color="#FFFFFF" size="20"></u-icon>
												</view>
												<view class="cross" v-else>跨境</view>
											</view>
										</view>
									</view>
								</view>
							</view>
						</z-paging>
					</view>
				</view>
				</scroll-view>
			</view>
		</view>
		<customer-service-suspension></customer-service-suspension>
		<tabbar id="tabbar"></tabbar>
	</view>
</template>
<script>
	import {
		mapState
	} from 'vuex'
	const shopPlugin = require('@/static/shopPlugin/api.js')
	import constDefine from '../../static/shopPlugin/constDefine'
	export default {
		data() {
			return {
				isLoading: true,
				residueHeight: 0,
				efficacyList: [], //功效列表
				categoryList: [], //分类列表
				currentIndex: 0,
				categoryIndex: 0,
				verticalNavTop: 0,
				tabInactiveStyle: {
					padding: '22rpx 31rpx',
					background: '#DEDEDE',
					lineHeight: '1',
					borderRadius: '34rpx',
					fontSize: '24rpx',
					color: '#FFFFFF',
				},
				tabActiveStyle: {
					padding: '22rpx 31rpx',
					background: '#000000',
					lineHeight: '1',
					borderRadius: '34rpx',
					fontSize: '24rpx',
					color: '#FFFFFF',
				},
				tabsItemStyle: {
					height: '114rpx'
				},
				params: {
					page: 1,
					pageSize: 10,
					order_type: 1, // 1: 默认排序, 2: 新品, 3: 价格
					price_order: 1, // 1: 升序, 2: 倒序
					efficacy_id: "",
					category_id: "",
					brand_id: "",
				},
				riseIconSrc: this.$getImageUrl('/user_client/static/icons/rise.png'),
				dropIconSrc: this.$getImageUrl('/user_client/static/icons/drop.png'),
				productList: [],
				total: 0,
				isShopCart: true,
				initialEfficacyList: [],
				searchCustomStyle: {
					backgroundColor: '#FFFFFF',
					padding: '4rpx 6rpx 4rpx 20rpx',
					borderRadius: "0rpx"
				},
				searchPlaceholderStyle: {
					fontSize: '28rpx',
					color: '#CACACA',
				},
				keyWord: ''
			}
		},
		onLoad(e) {
			uni.hideTabBar({
				success: () => {},
				fail: (ex) => {
					console.log(ex)
					// 捕获报错，防止没有tabbar页面调用后控制台报错
				}
			});
			if (e.parent_id) {
				uni.setStorageSync('parent_id', e.parent_id)
			}
		},
		computed: {
			...mapState({
				categoryId: (state) => state.init.categoryId,
				navbarHeight: (state) => state.init.navbarHeight,
				userInfo: (state) => state.user.userInfo,
			})
		},
		watch: {
			categoryId: {
				immediate: true,
				handler(newValue) {
					this.getCategory()
				}
			}
		},
		methods: {
			seekCategoryIndex() {
				const index = this.categoryList.findIndex(item => item.id === this.categoryId);
				if (index !== -1) {
					this.categoryChange(index)
				} else {
					this.categoryChange(0)
				}
			},
			getCategory() {
				this.$get("index/productCategoryOrBrand").then(res => {
					this.efficacyList = res.data.efficacy
					this.categoryList = res.data.category
					this.initialEfficacyList = JSON.parse(JSON.stringify(this.efficacyList)); // 保存初始化数据的副本
					this.getNavbarHeight()
				}).catch(ex => {
					this.$errorToast(ex)
				});
			},
			getNavbarHeight() {
				this.$nextTick(() => {
					const {
						platform,
						windowHeight
					} = uni.getSystemInfoSync();
					const query = uni.createSelectorQuery().in(this);
					query.select('#tabbar').boundingClientRect();
					query.exec(res => {
						const tabbarHeight = res[0].height;
						let systemInfo = uni.getSystemInfoSync(); //获取系统信息
						const windowHeight = systemInfo.screenHeight
						// 计算底部安全区域高度
						let bottomSafeAreaHeight = systemInfo.screenHeight - systemInfo.safeArea.bottom;
						const searchHeight = 156
						const headerHeight = 57 + 20
						if (platform === 'ios') {
							this.residueHeight = windowHeight -
								bottomSafeAreaHeight - 70 - searchHeight - headerHeight
						} else if (platform === 'android') {
							this.residueHeight = windowHeight - 70 - searchHeight -
								headerHeight
						} else {
							this.residueHeight = windowHeight - 70 - searchHeight -
								headerHeight
						}
						this.isLoading = false
						if (this.categoryId == '') {
							// 初始化参数
							this.params.efficacy_id = this.efficacyList[0].id
							this.params.category_id = this.categoryList[0].id
							this.seekCategoryIndex()
						} else {
							this.params.efficacy_id = this.efficacyList[this.currentIndex].id
							this.params.category_id = this.categoryList[this.categoryIndex].id
							this.seekCategoryIndex()
						}
					});
				})
			},
			// 获取产品列表
			getProductList(pageNo, pageSize) {
				var _this = this
				_this.params.page = pageNo || 1;
				_this.params.pageSize = pageSize || 10;
				_this
					.$get("product/efficacyCategoryGetProduct", _this.params)
					.then((res) => {
						_this.$refs.paging.complete(res.data.data);
						_this.total = res.data.total
					})
					.catch((ex) => {
						_this.$refs.paging.complete(false);
						console.log(ex)
						_this.$errorToast(ex)
					})
			},
			cateItemClick(item) {
				this.$navigateTo('/subPackages/search/list?mod_type=1&category_id=' + item.id)
			},
			productChange(item) {
				// 可做页面跳转等
				if (item.source_type == 2) {
					const id = item.yueyang_product_id
					shopPlugin.gotoProduct(id)
				} else {
					this.$navigateTo('/subPackages/product/product-detail?product_id=' + item.id)
				}
			},
			tabsClick(e) {
				if (this.currentIndex == e.index) return;
				this.currentIndex = e.index;
				if (this.efficacyList.length == 0) return;
				this.params.efficacy_id = this.efficacyList[this.currentIndex].id
				this.reset()
			},
			categoryChange(index) {
				this.categoryIndex = index;
				this.verticalNavTop = (index - 1) * 53;
				// 确保 categoryList 有数据
				if (this.categoryList.length === 0) return;
				// 更新参数
				this.params.category_id = this.categoryList[index].id;
				// 根据 id 决定 this.efficacyList 的值
				if (this.categoryList[index].id === 10023 || this.categoryList[index].id === 10024 ||
					this.categoryList[index].id === 10025 ||
					this.categoryList[index].id === 10026) {
					this.efficacyList = JSON.parse(JSON.stringify(this.initialEfficacyList)); // 恢复到初始化数据
					this.params.efficacy_id = this.efficacyList[this.currentIndex].id
				} else {
					this.params.efficacy_id = 0
					this.efficacyList = [{
						name: '全部'
					}]; // 使用假数据
					this.currentIndex = 0
				}
				// 更新状态
				this.reset();
			},
			// 重置产品列表
			reset() {
				this.params.page = 1
				this.productList = []
				this.getProductList()
			},
			setOrderType(type) {
				if (type === 2) {
					this.params.order_type = type;
					this.params.price_order = 1; // 新品排序时，默认为升序
					this.reset()
				} else if (type === 3) {
					this.params.order_type = type;
					// 如果之前是按价格排序，可以保持当前的 price_order 状态
					// 你可以根据需求调整默认值
					this.togglePriceOrder()
				} else {
					this.params.order_type = 1; // 默认排序
					this.params.price_order = 1; // 默认为升序
				}
			},
			togglePriceOrder() {
				// 切换价格排序的升序和倒序
				if (this.params.order_type === 3) {
					this.params.price_order = this.params.price_order === 1 ? 2 : 1;
				}
				this.reset()
			},
			// 添加购物车
			addShop(e) {
				if (!this.$isLogin()) {
					this.$navigateTo()
					return false;
				}
				if (this.isShopCart == false) return;
				this.isShopCart = false;
				this.$post("shopCart/addReduce", {
					product_type: 1, // 普通商品
					type: 1, // 加1
					product_id: e.id, // 商品id
					product_spec_id: e.minPriceSpec.id, // 规格id
				}).then(res => {
					this.isShopCart = true;
					this.$showToast(res.msg);
					if (res.code == 200) {
						// 更新购物车总数
						this.$store.commit('shopCart/setShopCartNumber', res.data.total);
						// 更新已购物车
						this.$store.commit('shopCart/setIsUpdate');
					}
				}).catch(ex => {
					this.isShopCart = true;
					this.$errorToast()
				});
			},
			// 搜索
			searchChange() {
				this.$navigateTo(`/subPackages/search/list?keyword=${this.keyWord}&mod_type=1`)
			}
		},
		onShareAppMessage() {
			const id = this.userInfo.id || ''
			return {
				path: `/pages/category/index?parent_id=${id}`
			};
		},
		// 分享到朋友圈
		onShareTimeline: function(res) {
			return this.$onShareTimeline()
		},
	}
</script>

<style>
	page {
		background-color: #FFFFFF;
	}
</style>

<style lang="scss" scoped>
	.container {
		.search {
			padding: 0 28rpx 40rpx 28rpx;
			box-sizing: border-box;

			.img {
				width: 28rpx;
				height: 26rpx;
				display: block;
			}

			.button {
				height: 56rpx;
				background-color: #000000;
				font-size: 28rpx;
				color: #CACACA;
				line-height: 56rpx;
				border-radius: 0rpx;
			}
		}

		.main {
			.header {
				padding: 0 28rpx 0 0;
				box-sizing: border-box;
			}

			.category {
				margin-top: 40rpx;

				.scroll-left {
					width: 176rpx;

					.category-left {

						.li {
							width: 176rpx;
							padding: 40rpx 0;
							line-height: 1;
							position: relative;
							background-color: #F5F5F5;
							font-size: 26rpx;
							color: #626262;

							.line {
								width: 8rpx;
								height: 58rpx;
								background: #000000;
								border-radius: 0rpx 8rpx 8rpx 0rpx;
								position: absolute;
								left: 0;
								top: 50%;
								transform: translateY(-50%);
							}
						}

						.li-active {
							color: #000000;
							background-color: #FFFFFF;
						}
					}
				}

				.category-right {
					flex: 1;
					position: relative;

					.right-header {
						padding: 10rpx 28rpx 10rpx 22rpx;
						box-sizing: border-box;
						width: 100%;
						position: sticky;
						top: -1rpx;
						left: 0;
						background-color: #FFFFFF;
						z-index: 9;

						.header-text {
							font-size: 28rpx;
							color: $base-price-color;
						}

						.header-right {
							.new {
								font-size: 28rpx;
								color: #8F8E8E;
								padding-right: 20rpx;
							}

							.new-active {
								font-size: 32rpx;
								color: #000000;
							}

							.header-icon {
								width: 24rpx;
								height: 24rpx;
								display: block;
							}
						}
					}

					.product {
						padding: 0 28rpx 0 22rpx;
						box-sizing: border-box;
						position: relative;

						.li {
							padding: 30rpx 0;
							border-bottom: 2rpx solid #EEEEEE;

							.li-img {
								box-shadow: 0rpx 6rpx 6rpx 2rpx rgba(0, 0, 0, 0.16);
								border-radius: 16rpx;
								position: relative;

								.img-11 {
									position: absolute;
									top: 0;
									right: 0;
									width: 52rpx;
									height: 44rpx;
									display: block;
								}

								.shop-618 {
									width: 68rpx;
									height: 64rpx;
									display: block;
									position: absolute;
									top: 0;
									right: 0;
									z-index: 9;
								}

								.shop-bybt {
									width: 64rpx;
									height: 34rpx;
									display: block;
									position: absolute;
									bottom: 0;
									left: 0;
									z-index: 9;
								}
							}

							.li-right {
								flex: 1;
								height: 164rpx;
								padding-left: 34rpx;

								.li-name {
									display: -webkit-box;
									-webkit-box-orient: vertical;
									-webkit-line-clamp: 2;
									overflow: hidden;
									font-size: 28rpx;
								}

								.li-footer {
									width: 100%;

									.footer-left {
										.li-price {
											padding-right: 10rpx;
										}

										.original-price {
											font-size: 20rpx;
											color: #A7A7A7;
											text-decoration: line-through;
											line-height: 38rpx;
										}

										.activity {
											.activity-img {
												width: 76rpx;
												height: 30rpx;
												display: block;
											}

											.activity-price {
												font-family: Source Han Sans CN, Source Han Sans CN;
												font-weight: 500;
												font-size: 18rpx;
												color: #FF3620;
												line-height: 1;
											}
										}
									}

									.footer-right {
										.shop-base {
											padding: 12rpx;
											border-radius: 50%;
											background-color: #000000;
										}

										.cross {
											padding: 8rpx 12rpx;
											box-sizing: border-box;
											background-color: #131313;
											border-radius: 2rpx;
											font-size: 20rpx;
											color: #FFFFFF;
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}
</style>